package com.fablesoft.projectdatacollect.ui.test;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.authentication.asynctask.AsyncFingerprint;
import com.fablesoft.projectdatacollect.MyApplication;
import com.fablesoft.projectdatacollect.R;
import com.fablesoft.projectdatacollect.bean.BaseResponse;
import com.fablesoft.projectdatacollect.bean.ItemFingerprint;
import com.fablesoft.projectdatacollect.http.BaseRequest;
import com.fablesoft.projectdatacollect.http.HttpListener;
import com.fablesoft.projectdatacollect.http.RequestUpload;
import com.fablesoft.projectdatacollect.util.CommonUtils;
import com.fablesoft.projectdatacollect.util.Config;
import com.fablesoft.projectdatacollect.view.DividerGridItemDecoration;
import com.fablesoft.projectdatacollect.view.XCRoundRectImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android_serialport_api.FingerprintAPI;

public class FragmentFingerprint extends BaseFragment {

    private RecyclerView rvFinger;
    private TextView readResult2;
    private Button btNext2;
    private Button btLast2;
    private HomeAdapter adapter;
    List<ItemFingerprint> fingers;
    private List<String> deleteId;
    private int currentPosition = 0;
    private AsyncFingerprint asyncFingerprint;
    int hasFinger[] = {0, 1, 2, 3, 4, 5, 6, 7};
    private DisplayImageOptions mOptions;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_fingerprint_info, container, false);
        initView();
        initData();
        initFinger();
        setSerialPort(true);
        return view;
    }

    @Override
    protected void initView() {
        super.initView();

        readResult2 = (TextView) view.findViewById(R.id.tv_fingerprint_tip);
        btNext2 = (Button) view.findViewById(R.id.next2);
        btLast2 = (Button) view.findViewById(R.id.last2);
        btNext2.setOnClickListener(this);
        btLast2.setOnClickListener(this);

        rvFinger = (RecyclerView) view.findViewById(R.id.rv_finger);
        rvFinger.setLayoutManager(new GridLayoutManager(mContext, 5));
        rvFinger.setAdapter(adapter = new HomeAdapter());
        rvFinger.addItemDecoration(new DividerGridItemDecoration(mContext));
    }

    @Override
    protected void initData() {
        super.initData();
        if (mOptions == null) {
            mOptions = new DisplayImageOptions.Builder()
                    .imageScaleType(ImageScaleType.IN_SAMPLE_INT)
                    .resetViewBeforeLoading(true).cacheOnDisc(false)
                    .cacheInMemory(true)
                    .bitmapConfig(Bitmap.Config.RGB_565)
                    .considerExifParams(true).build();
        }
        if (fingers == null) {
            fingers = new ArrayList<>();
        }
        if (deleteId == null) {
            deleteId = new ArrayList<>();
        }
        if (mActivity.result != null && mActivity.result.getData() != null && mActivity.result.getData().getFingerPrintPOS() != null) {
            Log.d(CommonUtils.TAG_UPLOAD, "FingerPrintPOS size = " + mActivity.result.getData().getFingerPrintPOS().size());
            for (ItemFingerprint item : mActivity.result.getData().getFingerPrintPOS()) {
                item.setItemName(getResources().getString(R.string.fingerprint_name, ++currentPosition));
                fingers.add(item);
                add(currentPosition - 1);
                if (currentPosition >= 8) {
                    return;
                }
            }
        }
        ItemFingerprint finger;
        for (int j = currentPosition; j < 8; j++) {
            finger = new ItemFingerprint(getResources().getString(R.string.fingerprint_name, j + 1));
            fingers.add(finger);
        }
        adapter.notifyDataSetChanged();
    }

    class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder> {

        @Override
        public HomeAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            HomeAdapter.MyViewHolder holder = new HomeAdapter.MyViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_fingerprint, parent,
                    false));
            return holder;
        }

        @Override
        public void onBindViewHolder(HomeAdapter.MyViewHolder holder, final int position) {
            final ItemFingerprint finger = fingers.get(position);
            holder.tv.setText(finger.getItemName());
            if (!TextUtils.isEmpty(finger.getFingerImagePath())) {
                String url = Config.BASE + finger.getFingerImagePath();
                url = url.replaceAll("\\\\", "/");
                Log.d(CommonUtils.TAG_UPLOAD, "finger path = " + url);
                ImageLoader.getInstance().displayImage(url, holder.iv, mOptions);
                holder.x.setVisibility(View.VISIBLE);
            } else if (finger.getBitmap() != null) {
                holder.iv.setImageBitmap(finger.getBitmap());
                holder.x.setVisibility(View.VISIBLE);
            } else {
                holder.iv.setImageResource(0);
                holder.x.setVisibility(View.GONE);
            }
            if (currentPosition == position) {
                holder.iv.setBackgroundResource(R.drawable.bule_dash_frame_bg);
            } else {
                holder.iv.setBackgroundResource(R.drawable.white_dash_frame_bg);
            }
            holder.x.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ItemFingerprint newFinger = new ItemFingerprint(finger.getItemName());
                    fingers.remove(finger);
                    if (!TextUtils.isEmpty(finger.getId())) {
                        deleteId.add(finger.getId());
                    }
                    delete(position);
                    currentPosition = getCurrentPostion();
                    fingers.add(position, newFinger);
                    notifyDataSetChanged();
                }
            });
        }

        @Override
        public int getItemCount() {
            return fingers.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView tv;
            ImageView x;
            XCRoundRectImageView iv;

            public MyViewHolder(View view) {
                super(view);
                tv = (TextView) view.findViewById(R.id.tv_item_fingername);
                x = (ImageView) view.findViewById(R.id.iv_item_delete);
                iv = (XCRoundRectImageView) view.findViewById(R.id.iv_item_finger);
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.next2:
                listener.onNext(2);
                break;
            case R.id.last2:
                listener.onLast(2);
                break;
        }
    }

    public void initFinger() {
        if (asyncFingerprint == null) {
            asyncFingerprint = new AsyncFingerprint(MyApplication.getInstance().getHandlerThread().getLooper(), mHandler);
            asyncFingerprint.setFingerprintType(FingerprintAPI.SMALL_FINGERPRINT_SIZE);
        }
    }

    public void clearFinger() {
        if (asyncFingerprint != null) {
            asyncFingerprint.setStop(true);
            asyncFingerprint.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public void setSerialPort(boolean enable) {
        if (asyncFingerprint == null) {
            return;
        }
        if (enable) {
            asyncFingerprint.setStop(false);
            asyncFingerprint.register();
        } else {
            asyncFingerprint.setStop(true);
        }
    }

    private void showFingerImage(byte[] data) {
        if (currentPosition >= 8) {
            setSerialPort(false);
            return;
        }
        ItemFingerprint fingerprint = new ItemFingerprint();
        String filename = "finger_" + System.currentTimeMillis();
        Bitmap image = BitmapFactory.decodeByteArray(data, 0, data.length);
        fingerprint.setFileName(filename);
        fingerprint.setImageBytes(data);
        fingerprint.setBitmap(image);
        fingerprint.setItemName(getResources().getString(R.string.fingerprint_name, ++currentPosition));
        fingers.remove(currentPosition - 1);
        fingers.add(currentPosition - 1, fingerprint);
        add(currentPosition - 1);
        currentPosition = getCurrentPostion();
        adapter.notifyDataSetChanged();
        setSerialPort(true);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        clearFinger();
    }

    private void add(int position) {
        for (int i = 0; i < hasFinger.length; i++) {
            if (position == hasFinger[i]) {
                hasFinger[i] = -1;
                break;
            }
        }
    }

    private void delete(int position) {
        for (int i = 0; i < hasFinger.length; i++) {
            if (-1 == hasFinger[i]) {
                hasFinger[i] = position;
                break;
            }
        }
        Arrays.sort(hasFinger);
    }

    private int getCurrentPostion() {
        for (int i = 0; i < hasFinger.length; i++) {
            if (-1 != hasFinger[i]) {
                return hasFinger[i];
            }
        }
        return hasFinger.length + 1;
    }

    public void submitFingerprintInfo() {
        List<ItemFingerprint> submitFingers = new ArrayList<>();
        for (ItemFingerprint item : fingers) {
            if (item.getBitmap() != null) {
                submitFingers.add(item);
            }
        }
        if (submitFingers.size() <= 0) {
            Log.d(CommonUtils.TAG_UPLOAD, "指纹信息为空，无法上传！");
            listener.onSubmitStatus(CommonUtils.UPLOAD_FINGERPRINT_IMAGE, true, false);
            return;
        }
        Map<String, Object> uploadFileparams = new HashMap<>();
        uploadFileparams.put("idNo", mActivity.idNo);
        uploadFileparams.put("deleteFileIds", CommonUtils.listToString(deleteId));
        Log.d(CommonUtils.TAG_UPLOAD, "指纹信息开始上传......param = " + uploadFileparams);

        new RequestUpload(Config.UPLOAD_FINGERS_URL, uploadFileparams,
                BaseRequest.KEY_FILE, submitFingers, BaseResponse.class, new HttpListener() {

            @Override
            public void onRequestFinish(BaseResponse response) {
                Message msg = mHandler.obtainMessage();
                msg.obj = response;
                msg.what = CommonUtils.UPLOAD_FINGERPRINT_IMAGE;
                mHandler.sendMessage(msg);
            }

            @Override
            public void onNotLogin(BaseResponse response) {
                mActivity.onNotLogin(response);
            }
        }).sendFilesRequest();

    }

    protected Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case AsyncFingerprint.SHOW_FINGER_IMAGE:
                    showFingerImage((byte[]) msg.obj);
                    break;
                case CommonUtils.UPLOAD_FINGERPRINT_IMAGE:
                    BaseResponse fingerResponse = (BaseResponse) msg.obj;
                    if (fingerResponse == null) {
                        listener.onSubmitStatus(CommonUtils.UPLOAD_FINGERPRINT_IMAGE, false, true);
                        return;
                    }
                    if (fingerResponse.getSuccess()) {
                        listener.onSubmitStatus(CommonUtils.UPLOAD_FINGERPRINT_IMAGE, true, false);
                    }
                    break;
            }
        }
    };

}
